/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller;

import dao.CountryDAO;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.Country;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 *
 * @author CAR
 */
public class CountryServlet extends HttpServlet {

public CountryServlet() {
        super();
    }
 
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
 
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String start = request.getParameter("start");
        String limit = request.getParameter("limit");
        String query = request.getParameter("query");

        PrintWriter out = response.getWriter();
        response.setContentType("text/html");

        JSONArray arrayObj=new JSONArray();

        CountryDAO countryDAO = new CountryDAO();
        ArrayList<Country> countryList = countryDAO.getItems(start,limit,query);
        for(int i=0;i<countryList.size();i++){
            Country country = countryList.get(i);
            JSONObject itemObj = JSONObject.fromObject(country);
            arrayObj.add(itemObj);
        }

        JSONObject myObj = new JSONObject();
        myObj.put("success", true);
        myObj.put("countries", arrayObj);
        myObj.put("totalCount", countryDAO.getTotalCount(query));

        out.println(myObj.toString());
        out.close();

    }
}
